<?php
declare(strict_types=1);

namespace App\Services;

use App\Models\YikaoMajors;
use App\Models\YikaoSpecialMajor;
use App\Models\YikaoSpecialDetail;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Monolog\Logger;

class YikaoSpecialDetailSpiderService
{
    private Client $httpClient;
    private Logger $logger;
    private string $baseUrl = 'https://static-data.gaokao.cn/www/2.0/special/%s/pc_special_detail.json?a=www.gaokao.cn';

    public function __construct(Client $httpClient, Logger $logger)
    {
        $this->httpClient = $httpClient;
        $this->logger = $logger;
    }

    /**
     * 获取所有待采集的艺术类专业
     * @param array|null $columns 指定需要的字段(null表示所有字段)
     * @return YikaoSpecialMajor[]
     */
    public function getSpecialMajors(?array $columns = null): array
    {
        $query = YikaoMajors::query()
            ->whereIn('level3', [271,264,236,121,122,124,123,125,205,206,208,207]);
        
        if ($columns !== null) {
            $query->select($columns);
        }
        
        return $query->get()->toArray();
    }

    /**
     * 采集专业详情数据
     * @param array $major 专业数据
     * @return bool 是否成功
     */
    public function crawlSpecialDetail(array $major): bool
    {
        try {
            $specialId = $major['special_id'] ?? null;
            if (empty($specialId)) {
                throw new \InvalidArgumentException('Missing special_id');
            }

            $url = sprintf($this->baseUrl, $specialId);
            $response = $this->httpClient->get($url);
            $data = json_decode((string)$response->getBody(), true);

            if (empty($data['data'])) {
                throw new \RuntimeException('Empty response data');
            }

            $detailData = $this->transformData($data['data'], $major);
            $this->saveDetail($detailData);

            $this->logger->info("Successfully crawled special detail", [
                'special_id' => $specialId,
                'name' => $major['name'] ?? ''
            ]);

            return true;
        } catch (GuzzleException $e) {
            $this->logger->error("HTTP request failed", [
                'error' => $e->getMessage(),
                'special_id' => $major['special_id'] ?? null
            ]);
        } catch (\Exception $e) {
            $this->logger->error("Crawl special detail failed", [
                'error' => $e->getMessage(),
                'special_id' => $major['special_id'] ?? null
            ]);
        }

        return false;
    }

    /**
     * 转换数据格式
     * @param array $apiData API返回数据
     * @param array $major 专业基础数据
     * @return array
     */
    private function transformData(array $apiData, array $major): array
    {
        return [
            'xyq_id' => $major['id'] ?? null,
            'name' => $apiData['name'] ?? $major['name'] ?? '',
            'code' => $apiData['code'] ?? '',
            'level1' => $apiData['level1'] ?? '',
            'level1_name' => $apiData['level1_name'] ?? '',
            'level2' => $apiData['level2'] ?? '',
            'level3' => $apiData['level3'] ?? '',
            'degree' => $apiData['degree'] ?? '',
            'limit_year' => $apiData['limit_year'] ?? '',
            'content' => $apiData['content'] ?? '',
            'course' => $apiData['course'] ?? '',
            'do_what' => $apiData['do_what'] ?? '',
            'learn_what' => $apiData['learn_what'] ?? '',
            'job' => $apiData['job'] ?? '',
            'jobdetail' => $apiData['jobdetail'] ?? [],
            'skill' => $apiData['skill'] ?? '',
            'celebrity' => $apiData['celebrity'] ?? '',
            'continue_exp' => $apiData['continue_exp'] ?? '',
            'is_what' => $apiData['is_what'] ?? '',
            'sel_adv' => $apiData['sel_adv'] ?? '',
            'status' => $apiData['status'] ?? '',
            'e_status' => $apiData['e_status'] ?? '',
            'senior_status' => $apiData['senior_status'] ?? '',
            'is_cancel' => $apiData['is_cancel'] ?? '',
            'type' => $apiData['type'] ?? '',
            'type_detail' => $apiData['type_detail'] ?? '',
            'tag' => $apiData['tag'] ?? '',
            'direction' => $apiData['direction'] ?? '',
            'samename' => $apiData['samename'] ?? '',
            'samenamearr' => $apiData['samenamearr'] ?? '',
            'rate' => $apiData['rate'] ?? '',
            'rate2' => $apiData['rate2'] ?? '',
            'salaryavg' => $apiData['salaryavg'] ?? '',
            'mostemploymentarea' => $apiData['mostemploymentarea'] ?? '',
            'mostemploymentindustry' => $apiData['mostemploymentindustry'] ?? '',
            'mostemployedeposition' => $apiData['mostemployedeposition'] ?? '',
            'jobbsgs' => $apiData['jobbsgs'] ?? '',
            'action_type' => $apiData['action_type'] ?? '',
            'action_special' => $apiData['action_special'] ?? [],
            'heat' => $apiData['heat'] ?? [],
            'impress' => $apiData['impress'] ?? [],
            'jobrate' => $apiData['jobrate'] ?? [],
            'professionalsalary' => $apiData['professionalsalary'] ?? [],
            'specialschool' => $apiData['specialschool'] ?? [],
            'video' => $apiData['video'] ?? [],
            'bxtj_myd' => $apiData['bxtj_myd'] ?? '',
            'bxtj_myd_vote_num' => $apiData['bxtj_myd_vote_num'] ?? 0,
            'jxzl_myd' => $apiData['jxzl_myd'] ?? '',
            'jxzl_myd_vote_num' => $apiData['jxzl_myd_vote_num'] ?? 0,
            'jy_myd' => $apiData['jy_myd'] ?? '',
            'jy_myd_vote_num' => $apiData['jy_myd_vote_num'] ?? 0,
            'zh_myd' => $apiData['zh_myd'] ?? '',
            'zh_myd_vote_num' => $apiData['zh_myd_vote_num'] ?? 0,
        ];
    }

    /**
     * 保存专业详情数据
     * @param array $data
     * @return void
     */
    private function saveDetail(array $data): void
    {
        YikaoSpecialDetail::query()->updateOrCreate(
            ['code' => $data['code']],
            $data
        );
    }
}
